<template>
  <div class="app-container">
    <!-- 顶部控制栏 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="searchForm.time" placeholder="时间范围" clearable @change="handleSearch">
            <el-option v-for="item in timeRangeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-select v-model="searchForm.waterQualityList" multiple collapse-tags placeholder="选择水质指标"
            style="width: 100%" @change="handleSearch">
            <el-option v-for="item in waterQualityOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 水质指标概览 -->
    <el-card class="mt-2">
      <div class="section-title">水质指标概览</div>
      <el-row :gutter="20">
        <el-col :span="4" v-for="(indicator, index) in indicatorOverview" :key="index">
          <div class="indicator-item" :class="{ 'abnormal': indicator.status !== '正常' }">
            <div class="indicator-name">{{ indicator.name }}</div>
            <div class="indicator-value">{{ indicator.value }}</div>
            <div class="indicator-standard"> {{ indicator.standard }}</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 主内容区 -->
    <div class="main-content mt-2">
      <!-- 实时监测模块 -->
      <template v-if="activeTab === 'realtime'">
        <!-- 实时水质指标 -->
        <el-card class="realtime-indicators">
          <div class="section-title">实时水质指标</div>
          <div class="time-range">更新时间: {{ realtimeData.updateTime }}</div>
          <el-row :gutter="20">
            <el-col :span="8" v-for="(indicator, index) in realtimeData.indicators" :key="index">
              <el-card shadow="always" class="mt-2">
                <div class="metric-card">
                  <div class="metric-name">{{ indicator.name }}</div>
                  <div class="metric-value">{{ indicator.realtimeValue }}</div>
                  <div class="metric-standard">标准值: {{ indicator.standardValue }}</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>

        <!-- 水质趋势分析 -->
        <el-card class="trend-analysis">
          <div class="section-title">水质趋势分析</div>
          <div class="time-range">时间范围: {{ searchForm.time }}</div>
          <ECharts :option="trendChartOption" style="height: 400px;" />
        </el-card>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-card>
              <div class="section-title">指标达标率</div>
              <ECharts :option="complianceChartOption" style="height: 300px;" />
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <div class="section-title">异常数据统计</div>
              <ECharts :option="exceptionChartOption" style="height: 300px;" />
            </el-card>
          </el-col>
        </el-row>
      </template>

      <!-- 历史数据模块 -->
      <template v-else>
        <!-- 水质综合评分 -->
        <el-card class="score-card">
          <div class="section-title">水质综合评分</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="score-value">
                <div class="score">{{ comprehensiveScore }}</div>
                <div class="score-label">综合评分</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="compliance-rate">
                <div class="rate-title">指标达标率</div>
                <ECharts :option="miniComplianceChartOption" style="height: 200px;" />
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 异常数据统计 -->
        <el-card class="exception-stats">
          <div class="section-title">异常数据统计</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <ECharts :option="exceptionBarChartOption" style="height: 300px;" />
            </el-col>
            <el-col :span="12">
              <div class="exception-list">
                <div class="exception-item" v-for="(item, index) in exceptionData" :key="index">
                  <div class="exception-metric">{{ item.name }}</div>
                  <div class="exception-count">{{ item.value }}</div>
                  <el-progress :percentage="(item.value / maxExceptionCount) * 100" :show-text="false"
                    :color="exceptionColors[index % exceptionColors.length]" />
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </template>

      <!-- 详细水质数据 (共用模块) -->
      <el-card class="detail-data">
        <div class="section-title">详细水质数据</div>
        <el-table :data="detailData" border style="width: 100%" v-loading="loading">
          <el-table-column prop="time" label="时间" width="180" />
          <el-table-column prop="ph" label="pH值" />
          <el-table-column prop="turbidity" label="浊度(NTU)" />
          <el-table-column prop="cod" label="COD(mg/L)" />
          <el-table-column prop="ammoniaNitrogen" label="氨氮(mg/L)" />
          <el-table-column prop="dissolvedOxygen" label="溶解氧(mg/L)" />
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === '正常' ? 'success' : 'danger'" size="small">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import ECharts from '@/components/ECharts'
import {
  getTimeRangeList,
  getWaterQualityIndicatorList,
  getRealtimeWaterQualityIndex,
  getWaterQualityStandardRate,
  getWaterQualityTrend,
  getWaterQualityExceptionData,
  getWaterQualityComprehensiveScore,
  getWaterQualityDetailData
} from '@/api/prod_operate/water/manage/analyze'

// 搜索表单
const searchForm = reactive({
  time: '',
  waterQualityList: []
})

// 加载状态
const loading = ref(false)

// 时间范围选项
const timeRangeOptions = ref([])

// 水质指标选项
const waterQualityOptions = ref([])

// 当前激活的标签页
const activeTab = ref('realtime')

// 指标概览数据
const indicatorOverview = ref([])

// 实时数据
const realtimeData = ref({
  updateTime: '',
  indicators: []
})

// 详细水质数据
const detailData = ref([])

// 异常数据
const exceptionData = ref([])

// 综合评分
const comprehensiveScore = ref(0)

// 异常数据颜色
const exceptionColors = ['#F56C6C', '#E6A23C', '#409EFF', '#67C23A', '#909399']

// 最大异常数量
const maxExceptionCount = computed(() => {
  return exceptionData.value.length > 0
    ? Math.max(...exceptionData.value.map(item => item.value))
    : 1
})

// 新增趋势数据响应式变量
const trendData = reactive({
  dateList: [],
  series: []
})


// 获取时间范围列表
const fetchTimeRangeList = async () => {
  try {
    const { data } = await getTimeRangeList()
    timeRangeOptions.value = data || []
  } catch (error) {
    ElMessage.error('获取时间范围列表失败')
  }
}

// 获取水质指标列表
const fetchWaterQualityList = async () => {
  try {
    const { data } = await getWaterQualityIndicatorList()
    waterQualityOptions.value = data || []
  } catch (error) {
    ElMessage.error('获取水质指标列表失败')
  }
}

// 获取实时水质指标
const fetchRealtimeWaterQuality = async () => {
  try {
    loading.value = true
    const { data } = await getRealtimeWaterQualityIndex(searchForm)
    realtimeData.value = data || { updateTime: '', indicators: [] }

    // 更新指标概览
    updateIndicatorOverview(data?.indicators || [])
  } catch (error) {
    ElMessage.error('获取实时水质指标失败')
  } finally {
    loading.value = false
  }
}

// 获取指标达标率
const fetchWaterQualityStandardRate = async () => {
  try {
    const { data } = await getWaterQualityStandardRate(searchForm)
    return data || []
  } catch (error) {
    ElMessage.error('获取指标达标率失败')
    return []
  }
}

// 修改后的获取趋势数据函数
const fetchWaterQualityTrend = async () => {
  try {
    const { data } = await getWaterQualityTrend(searchForm)
    if (data) {
      trendData.dateList = data.dateList || []
      trendData.series = data.series || []
    }
    return data || { dateList: [], series: [] }
  } catch (error) {
    ElMessage.error('获取水质趋势分析失败')
    return { dateList: [], series: [] }
  }
}

// 获取异常数据统计
const fetchWaterQualityExceptionData = async () => {
  try {
    const { data } = await getWaterQualityExceptionData(searchForm)
    exceptionData.value = data?.indicatorNames?.map((name, index) => ({
      name,
      value: data.values[index] || 0
    })) || []
    return data || { indicatorNames: [], values: [] }
  } catch (error) {
    ElMessage.error('获取异常数据统计失败')
    return { indicatorNames: [], values: [] }
  }
}

// 获取水质综合评分
const fetchWaterQualityComprehensiveScore = async () => {
  try {
    const { data } = await getWaterQualityComprehensiveScore(searchForm)
    comprehensiveScore.value = data?.values?.[0] || 0
    return data || { indicatorNames: [], values: [] }
  } catch (error) {
    ElMessage.error('获取水质综合评分失败')
    return { indicatorNames: [], values: [] }
  }
}

// 获取详细水质数据
const fetchWaterQualityDetailData = async () => {
  try {
    loading.value = true
    const { data } = await getWaterQualityDetailData(searchForm)
    detailData.value = data ? [data] : []
  } catch (error) {
    ElMessage.error('获取详细水质数据失败')
    detailData.value = []
  } finally {
    loading.value = false
  }
}

// 更新指标概览
const updateIndicatorOverview = (indicators) => {
  indicatorOverview.value = indicators.map(indicator => ({
    name: indicator.name,
    value: indicator.realtimeValue,
    standard: indicator.standardValue,
    status: calculateStatus(indicator)
  }))
}

// 计算状态
const calculateStatus = (indicator) => {
  // 这里根据实际业务逻辑判断指标是否正常
  // 示例逻辑，实际应根据标准值判断
  const value = parseFloat(indicator.realtimeValue)
  if (isNaN(value)) return '未知'

  // 假设标准值是类似 "6.5~8.5" 或 "≤1" 的格式
  const standard = indicator.standardValue
  if (standard.includes('~')) {
    const [min, max] = standard.split('~').map(Number)
    return value >= min && value <= max ? '正常' : '异常'
  } else if (standard.startsWith('≤')) {
    const max = Number(standard.substring(1))
    return value <= max ? '正常' : '异常'
  } else if (standard.startsWith('≥')) {
    const min = Number(standard.substring(1))
    return value >= min ? '正常' : '异常'
  }
  return '未知'
}

// 计算百分比
const calculatePercentage = (indicator) => {
  const value = parseFloat(indicator.realtimeValue)
  if (isNaN(value)) return 0

  const standard = indicator.standardValue
  if (standard.includes('~')) {
    const [min, max] = standard.split('~').map(Number)
    return ((value - min) / (max - min)) * 100
  } else if (standard.startsWith('≤')) {
    const max = Number(standard.substring(1))
    return (value / max) * 100
  } else if (standard.startsWith('≥')) {
    const min = Number(standard.substring(1))
    return value >= min ? 100 : 0
  }
  return 0
}

// 获取进度条颜色
const getProgressColor = (indicator) => {
  const percentage = calculatePercentage(indicator)
  if (percentage < 30) return '#F56C6C'
  if (percentage < 70) return '#E6A23C'
  return '#67C23A'
}

// 搜索处理
const handleSearch = async () => {
  try {
    loading.value = true
    await Promise.all([
      fetchRealtimeWaterQuality(),
      fetchWaterQualityDetailData()
    ])

    if (activeTab.value === 'realtime') {
      await Promise.all([
        fetchWaterQualityStandardRate(),
        fetchWaterQualityTrend(),
        fetchWaterQualityExceptionData()
      ])
    } else {
      await Promise.all([
        fetchWaterQualityComprehensiveScore(),
        fetchWaterQualityExceptionData()
      ])
    }
  } catch (error) {
    console.error('搜索失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.time = ''
  searchForm.waterQualityList = []
  handleSearch()
}
// 修改后的趋势图表配置
const trendChartOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: trendData.series.map(item => item.name),
      textStyle: {
        color: '#333'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: trendData.dateList,
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: trendData.series.map(item => ({
      name: item.name,
      type: 'line',
      data: item.data,
      smooth: true,
      lineStyle: {
        width: 3
      },
      itemStyle: {
        color: (params) => exceptionColors[params.dataIndex % exceptionColors.length]
      }
    }))
  }
})

// 达标率图表配置
const complianceChartOption = computed(() => {
  return {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '达标率',
        type: 'pie',
        radius: ['50%', '70%'],
        data: [
          { value: 80, name: '达标' },
          { value: 20, name: '不达标' }
        ]
      }
    ]
  }
})

// 异常数据图表配置
const exceptionChartOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: exceptionData.value.map(item => item.name)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '异常数据',
        type: 'bar',
        data: exceptionData.value.map(item => item.value),
        itemStyle: {
          color: (params) => exceptionColors[params.dataIndex % exceptionColors.length]
        }
      }
    ]
  }
})

// 综合评分图表配置
const miniComplianceChartOption = computed(() => {
  return {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '达标率',
        type: 'pie',
        radius: ['70%', '90%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: comprehensiveScore.value, name: '综合评分' },
          { value: 100 - comprehensiveScore.value, name: '' }
        ]
      }
    ]
  }
})

// 异常数据条形图配置
const exceptionBarChartOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: exceptionData.value.map(item => item.name)
    },
    series: [
      {
        name: '异常次数',
        type: 'bar',
        data: exceptionData.value.map(item => item.value),
        itemStyle: {
          color: (params) => exceptionColors[params.dataIndex % exceptionColors.length]
        }
      }
    ]
  }
})

onMounted(() => {
  fetchTimeRangeList()
  fetchWaterQualityList()
  handleSearch()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-tag {
  margin-right: 5px;
}

/* 详情页样式 */
.detail-container {
  padding: 10px;
}

.detail-container h3 {
  margin: 20px 0 15px 0;
  color: #606266;
}

.mt-2 {
  margin-top: 20px;
}

/* 指标概览样式 */
.indicator-overview {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.indicator-item {
  padding: 15px;
  text-align: center;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.indicator-item.abnormal {
  border-left: 4px solid #f56c6c;
}

.indicator-name {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.indicator-value {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.indicator-standard {
  font-size: 12px;
  color: #909399;
}

/* 主内容区样式 */
.main-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 指标卡片样式 */
.metric-card {
  margin-top: 20px;
}

.metric-name {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.metric-standard {
  font-size: 12px;
  color: #909399;
  margin-bottom: 10px;
}

/* 时间范围样式 */
.time-range {
  font-size: 13px;
  color: #909399;
  margin-bottom: 15px;
}

/* 图表容器样式 */
.chart-container {
  width: 100%;
  height: 300px;
}

.mini-chart {
  width: 100%;
  height: 100px;
}

/* 综合评分样式 */
.score-card {
  margin-bottom: 20px;
}

.score-value {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.score {
  font-size: 48px;
  font-weight: bold;
  color: #409EFF;
}

.score-label {
  font-size: 14px;
  color: #606266;
}

.compliance-rate {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.rate-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

/* 异常数据列表样式 */
.exception-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 10px;
}

.exception-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.exception-metric {
  width: 80px;
  font-size: 14px;
}

.exception-count {
  width: 30px;
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .control-bar {
    flex-direction: column;
    align-items: flex-start;
  }

  .indicator-overview .el-col {
    margin-bottom: 10px;
  }
}
</style>